// 文件系统状态
let currentPath = '';
let files = [];

// DOM元素
const fileListElement = document.getElementById('fileList');
const createFolderBtn = document.getElementById('createFolderBtn');
const uploadFileBtn = document.getElementById('uploadFileBtn');
const fileInput = document.getElementById('fileInput');
const modal = document.getElementById('modal');
const modalBody = document.getElementById('modalBody');
const closeModal = document.getElementById('closeModal');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    currentPath = '';
    loadFileList();
    createFolderBtn.addEventListener('click', showCreateFolderModal);
    uploadFileBtn.addEventListener('click', () => fileInput.click());
    fileInput.addEventListener('change', handleFileUpload);
    closeModal.addEventListener('click', () => {modal.style.display = 'none';console.log('Modal closed')});
});

function loadFileList() {
    fetch(`/api/files?path=${currentPath}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            
        }
    })
    .then(response => {
        if (!response.ok) {
            alert('加载文件列表失败：请确认已登录或检查网络连接。');
            throw new Error('未登录或其他错误');
        }
        return response.json();
    })
    .then(data => {
        files = data;
        renderFileList();
    })
    .catch(error => console.error('加载文件列表失败:', error));
}

function renderFileList() {
    fileListElement.innerHTML = '';

    files.forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';

        fileItem.innerHTML = `
            <div class="file-info">
                <span class="file-name">${file.name}</span>
                <span class="file-type">${file.isDirectory ? '文件夹' : '文件'}</span>
                <span class="file-size">${(file.size/1024/1024).toFixed(2) || ''}MB</span>
                <span class="file-modified">${file.modified}</span>
            </div>
            <div class="file-actions">
                ${file.isDirectory ? 
                    `<button class="open-folder" data-path="${file.path}">打开</button>` : ''}
                ${file.name !== '..' ? 
                    `<button class="rename-file" data-path="${file.path}">重命名</button>
                     <button class="delete-file" data-path="${file.path}">删除</button>` : ''}
            </div>
        `;

        fileListElement.appendChild(fileItem);
    });

    document.querySelectorAll('.open-folder').forEach(btn => {
        btn.addEventListener('click', () => openFolder(btn.dataset.path));
    });

    document.querySelectorAll('.rename-file').forEach(btn => {
        btn.addEventListener('click', () => showRenameModal(btn.dataset.path));
    });

    document.querySelectorAll('.delete-file').forEach(btn => {
        btn.addEventListener('click', () => deleteFile(btn.dataset.path));
    });
}

function openFolder(path) {
    currentPath = path;
    document.querySelector('.path').textContent = currentPath;
    loadFileList();
}

function createFolder() {
    const folderName = document.getElementById('folderName').value;
    if (!folderName) return;

    fetch('/api/folder', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            
        },
        body: JSON.stringify({ name: folderName, path: currentPath })
    })
    .then(response => {
        if (response.ok) {
            loadFileList();
            modal.style.display = 'none';
        } else {
            response.json().then(err => alert(`创建失败: ${err.error}`));
        }
    })
    .catch(error => console.error('创建文件夹错误:', error));
}

function handleFileUpload(event) {
    const files = event.target.files;
    if (files.length === 0) return;

    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i]);
    }
    formData.append('path', currentPath);

    // 显示加载动画
    document.getElementById('upload-loading').style.display = 'block';

    fetch('/api/upload', {
        method: 'POST',
        headers: {
            
        },
        body: formData
    })
    .then(response => {
        if (response.ok) {
            return response.json().then(data => {
                alert(`${data.message}: ${data.filenames.join(', ')}`);
                loadFileList();
            });
        } else {
            return response.json().then(err => {
                alert(`上传失败: ${err.error}`);
            });
        }
    })
    .catch(error => {
        console.error('上传错误:', error);
        alert('上传过程中发生错误。');
    })
    .finally(() => {
        // 无论成功与否，隐藏加载动画
        document.getElementById('upload-loading').style.display = 'none';
    });
}

function renameFile(filePath) {
    const newName = document.getElementById('newName').value;
    if (!newName) return;

    fetch('/api/rename', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            
        },
        body: JSON.stringify({ path: filePath, newName: newName })
    })
    .then(response => {
        if (response.ok) {
            loadFileList();
            modal.style.display = 'none';
        } else {
            response.json().then(err => alert(`重命名失败: ${err.error}`));
        }
    })
    .catch(error => console.error('重命名错误:', error));
}

function deleteFile(file_path) {
    if (!confirm('确定要删除这个文件吗？')) return;

    fetch('/api/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            
        },
        body: JSON.stringify({ path: file_path })
    })
    .then(response => {
        if (response.ok) {
            loadFileList();
        } else {
            response.json().then(err => alert(`删除失败: ${err.error}`));
        }
    })
    .catch(error => console.error('删除错误:', error));
}

function showRenameModal(file_path) {
    const file = files.find(f => f.path === file_path);
    const currentName = file ? file.name : '';

    modalBody.innerHTML = `
        <h2>重命名</h2>
        <div class="form-group">
            <label for="newName">新名称</label>
            <input type="text" id="newName" value="${currentName}">
        </div>
        <button id="renameConfirm">确认</button>
    `;

    modal.style.display = 'block';
    document.getElementById('renameConfirm').addEventListener('click', () => renameFile(file_path));
}

function showCreateFolderModal() {
    modalBody.innerHTML = `
        <h2>新建文件夹</h2>
        <div class="form-group">
            <label for="folderName">文件夹名称</label>
            <input type="text" id="folderName" placeholder="输入文件夹名称">
        </div>
        <button id="createFolderConfirm">创建</button>
    `;

    modal.style.display = 'block';

    document.getElementById('createFolderConfirm').addEventListener('click', createFolder);
}